
// pages/order-summary/order-summary.js
import {calculateOrder, createOrder, getOrderCoupon} from "../../api/api";
import get from "../../utils/request";

Page({
  data: {
    products: [],
    couponList:[],
    couponName: '选择优惠券',
    couponCount: 0,
    voucherId: 0,
    couponDiscount: 0,
    vipDisicount: 0,
    totalItems: 1,
    subtotal: 0,
    phone: '',
    remark: '',
    selectedCoupon: '',
    paymentOptions: [
      { id: 1, value: 'wechat', label: '微信', checked: true },
      { id: 2, value: 'alipay', label: '支付宝', checked: false }
    ],
    total: 0
  },
  onShow() {
    const products = []
    getApp().globalData.selectedProduct.forEach((item) => {
      let specifications_v = ''
      console.log(item.specifications_s)
      Object.values(item.specifications_s).forEach((v,i,array) => {
        specifications_v += v + (i < array.length - 1?',':'')
      })
      item.specifications_v = specifications_v
      products.push(item)
    })
    this.setData({
      products: products,
      phone: getApp().globalData.phone,
      totalItems: getApp().globalData.count,
      selectedCoupon: getApp().globalData.selectedCoupon
    })

    if(getApp().globalData.selectedCoupon !== ''){
      this.setData({
        couponName: getApp().globalData.selectedCoupon.name,
        voucherId: getApp().globalData.selectedCoupon.id
      })
    }
    console.log( getApp().globalData.selectedProduct)

    const commodityList = getApp().globalData.selectedProduct.map(item => {
      return {id: item.id}
    })
    getOrderCoupon({commodityList:commodityList})
        .then(res => {
          this.setData({
            couponList: res.data,
            couponCount: res.data.length
          })
        })

    const _this =  this
    setTimeout(function() {
      _this.handleCalculate()
    })
  },
  /** 计算订单  */
  handleCalculate() {
    // 处理支付逻辑
    const commodityList = []
    this.data.products.forEach(item => {
      const obj = {
        id: item.id,
        name: item.name,
        amount: item.count,
        specifications: JSON.stringify(item.specifications_s)
      }

      commodityList.push(obj)
    })
    calculateOrder({
      voucherId: this.data.voucherId,
      commodityList
    }).then(r => {
      this.setData({
        total: r.data.actualPrice,
        couponDiscount: r.data.couponDiscount,
        vipDisicount: r.data.vipDisicount,
        subtotal: r.data.orderPrice
      })
    })
  },
  linkToCoupon(){
    getApp().globalData.couponList = this.data.couponList
    wx.navigateTo({
      url: '/pages/coupon/coupon?isPay=1',
    })
  },
  remarkInput(e){
    this.setData({
      remark: e.detail.value
    })
  },
  handlePay() {
    // 处理支付逻辑
    const commodityList = []
    this.data.products.forEach(item => {
      const obj = {
        id: item.id,
        name: item.name,
        amount: item.count,
        specifications: JSON.stringify(item.specifications_s)
      }

      commodityList.push(obj)
    })

    createOrder({
      commodityList,
      voucherId: this.data.voucherId,
      payType: 0,
      note: this.data.remark
    }).then(res => {
      if(res.data.ispay){
        wx.showToast({
          title: '支付成功',
          icon: 'none',
          duration: 2000,
        })

        setTimeout(function() {
          wx.switchTab({
            url: '/pages/order/order'
          })
        }, 2000)

        return
      }
      wx.requestPayment({
        timeStamp: res.data.wx.timestamp,
        nonceStr: res.data.wx.noncestr,
        package: res.data.wx.package,
        signType: res.data.wx.signType,
        paySign: res.data.wx.paySign,
        success(res) {
          getApp().globalData.couponList = []
          getApp().globalData.selectedProduct = []
          getApp().globalData.selectedCoupon = ''
          getApp().globalData.count = 0
          getApp().globalData.total = 0
          wx.showToast({
            title: '支付成功',
            icon: 'none',
            duration: 2000,
          })

          setTimeout(function() {
            wx.switchTab({
              url: '/pages/order/order'
            })
          }, 2000)
        },
        fail(res) {
          wx.showToast({
            title: '支付失败',
            icon: 'none'
          })
        }
      })
    })
  },
  
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    getApp().globalData.selectedCoupon = ''
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    getApp().globalData.selectedCoupon = ''
  },
});
